import javax.swing.*;
import java.awt.*;

class ExpenseManagement extends JFrame {
    private JTextField expenseSourceField, expenseTimeField, expenseAmountField;
    private JButton saveButton, backButton;
    private FamilyFinanceManager mainFrame;

    public ExpenseManagement(FamilyFinanceManager mainFrame) {
        this.mainFrame = mainFrame;
        setTitle("支出管理");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(300, 200);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(4, 2));

        panel.add(new JLabel("支出来源:"));
        expenseSourceField = new JTextField();
        panel.add(expenseSourceField);

        panel.add(new JLabel("支出时间 (yyyy-MM-dd):"));
        expenseTimeField = new JTextField();
        panel.add(expenseTimeField);

        panel.add(new JLabel("支出金额:"));
        expenseAmountField = new JTextField();
        panel.add(expenseAmountField);

        saveButton = new JButton("保存");
        backButton = new JButton("返回");

        panel.add(saveButton);
        panel.add(backButton);

        add(panel, BorderLayout.CENTER);

        addListeners();
    }

    private void addListeners() {
        saveButton.addActionListener(e -> {
            String source = expenseSourceField.getText();
            String time = expenseTimeField.getText();
            String amount = expenseAmountField.getText();
            if (!source.isEmpty() && !time.isEmpty() && !amount.isEmpty()) {
                DataManager.addExpense(source, time, amount);
                JOptionPane.showMessageDialog(this, "支出数据已保存");
                mainFrame.setVisible(true);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "请填写所有字段", "警告", JOptionPane.WARNING_MESSAGE);
            }
        });

        backButton.addActionListener(e -> {
            mainFrame.setVisible(true);
            dispose();
        });
    }
}